package com.vf.admin.miaodong.controller;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.vf.admin.client.service.*;
import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.AppGift;
import com.vf.admin.miaodong.entity.AppSetup;
import com.vf.admin.miaodong.service.AfterGiftService;
import com.vf.admin.utils.Base64Image.FileUtil;
import com.vf.admin.utils.StringEx;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.vf.admin.utils.StringEx.isNull;

/**
 * 礼物管理
 *
 * @author anxiang
 */
@Controller
@RequestMapping("/after/gift")
public class AfterGiftController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AfterGiftService afterGiftService;
    @Autowired
    AppUserGiftService appUserGiftService;
    @Autowired
    AppMingXiShouLiService appMingXiShouLiService;
    @Autowired
    AppMingXiSongLiService appMingXiSongLiService;
    @Autowired
    private AppSetupService appSetupService;
    @Autowired
    private AppUserService appUserService;

    /**
     * 礼物列表
     *
     * @param splitPage 分页
     * @param giftname  礼物名
     * @return
     */
    @RequestMapping("/list")
    public String list(SplitPageBean splitPage, String giftname) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("giftname", giftname);
            List<AppGift> list = afterGiftService.findList(map, splitPage);
            request.setAttribute("list", list);
            request.setAttribute("giftname", giftname);
            request.setAttribute("splitPage", splitPage);
            return this.sucess("/web/after/gift/list");
        } catch (Exception e) {
            logger.error("礼物管理异常", e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 添加礼物跳转
     *
     * @return
     */
    @RequestMapping("/add")
    public String add() {
        try {
            return this.sucess("/web/after/gift/add");
        } catch (Exception e) {
            logger.error("获取礼物详情异常", e);
            return this.error("系统繁忙");
        }
    }

    /**
     * 添加礼物跳转
     *
     * @param id id
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Integer id) {
        try {
            AppGift AppGift = afterGiftService.get(id);
            request.setAttribute("AppGift", AppGift);
            return this.sucess("/web/after/gift/edit");
        } catch (Exception e) {
            logger.error("获取礼物详情异常", e);
            return this.error("系统繁忙");
        }
    }

    @ResponseBody
    @RequestMapping("/uploadLiveImg")
    public Result uploadLiveImg(MultipartFile[] file) {
        try {
            String pic = "";
            //上传：循环获取file数组中得文件
            StringBuffer stringBuffer = new StringBuffer();
            if (file != null && file.length > 0) {
                MultipartFile files = file[0];
                if (!files.isEmpty()) {
                    //判断图片大小
                    if (files.getSize() <= 52428800) {
                        //上传阿里云oss
                        String ossUrl = appUserService.aliyunOssupload(files);
                        if (isNull(ossUrl)) {
                            return errorJSON("文件上传失败");
                        }
                        //拼接
                        stringBuffer.append(ossUrl);
                    } else {
                        return this.errorJSON("文件大小超过限制！");
                    }
                }
            } else {
                return this.errorJSON("文件不能为空");
            }
            pic = stringBuffer.toString();
            Map<String, String> mm = new HashMap<>();
            mm.put("name", pic);
            mm.put("imgname", "");
            return this.sucessJSON(mm, "保存成功");
        } catch (Exception e) {
            return this.errorJSON("系统繁忙");
        }
    }


    @ResponseBody
    @RequestMapping("/upOssImg")
    public Result upOssImg(MultipartFile[] file) {
        try {
            String pic = "";
            //上传：循环获取file数组中得文件
            StringBuffer stringBuffer = new StringBuffer();
            if (file != null && file.length > 0) {
                MultipartFile files = file[0];
                if (!files.isEmpty()) {
                    //判断图片大小
                    if (files.getSize() <= 52428800) {
                        //上传阿里云oss
                        String ossUrl = appUserService.aliyunOssupload(files);
                        if (isNull(ossUrl)) {
                            return errorJSON("文件上传失败");
                        }
                        //拼接
                        stringBuffer.append(ossUrl);
                    } else {
                        return this.errorJSON("文件大小超过限制！");
                    }
                }
            } else {
                return this.errorJSON("文件不能为空");
            }
            pic = stringBuffer.toString();
            Map<String, String> mm = new HashMap<>();
            mm.put("name", pic);
            mm.put("imgname", "");
            return this.sucessJSON(mm, "保存成功");
        } catch (Exception e) {
            return this.errorJSON("系统繁忙");
        }
    }


    /**
     * 新增礼物
     *
     * @param appGift 实体类
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Result saveliwu(AppGift appGift) {
        try {
            if (StringEx.isNull(appGift.getGiftname())) {
                return this.errorJSON("礼物名称不能为空");
            }
            if (StringEx.isNull(appGift.getPicture())) {
                return this.errorJSON("图片不能为空");
            }
            if (StringEx.isNull(appGift.getGoldmoney())) {
                return this.errorJSON("金币/钻石单价不能为空");
            }
            if (appGift.getId() != null) {
                AppGift sGift = afterGiftService.get(appGift.getId());

                if (sGift.getPicture().equals(appGift.getPicture())) {
                    sGift.setPicture(appGift.getPicture());
                } else {
                    //处理图片
                    String newfilePath = "";
                    Map map = FileUtil.aliyunOSSUpload(appGift.getPicture(), "");
                    if (map.get("st").equals("0")) {
                        newfilePath = (String) map.get("data");
                    }
                    if (StringEx.isNotNull(newfilePath)) {
                        sGift.setPicture(newfilePath);
                    }
                }
                sGift.setGiftname(appGift.getGiftname());
                sGift.setGoldmoney(appGift.getGoldmoney());
                sGift.setStatus(appGift.getStatus() == null ? Constants.shiFou_STATE_FOU : appGift.getStatus());
                if (StringUtils.isNotBlank(appGift.getSvgaaddress())) {
                    String gifteffects = appGift.getSvgaaddress().substring(appGift.getSvgaaddress().indexOf("/test/") + 6, appGift.getSvgaaddress().indexOf(".svga"));
                    sGift.setGifteffects(gifteffects);
                }
                sGift.setVersion(appGift.getVersion());
                sGift.setSvgaaddress(appGift.getSvgaaddress());
                sGift.setRemarks(appGift.getRemarks());
                sGift.setGoumaifangshi(appGift.getGoumaifangshi());
                sGift.setShifouquanfu(appGift.getShifouquanfu() == null ? Constants.shiFou_STATE_FOU : appGift.getShifouquanfu());
                sGift.setShifouguizu(appGift.getShifouguizu() == null ? Constants.shiFou_STATE_FOU : appGift.getShifouguizu());
                sGift.setLiwuguishu(appGift.getLiwuguishu());
                sGift.setIntimacy(appGift.getIntimacy());
                sGift.setIsBeckoning(appGift.getIsBeckoning());
                afterGiftService.save(sGift);
                //变更用户礼物强礼物图片
                appUserGiftService.uodateData(sGift.getId(), sGift.getPicture(), appGift.getGiftname());
                //变更收礼明细礼物图片
                appMingXiShouLiService.updateGiftData(sGift.getId(), sGift.getPicture(), appGift.getGiftname());
                //变更送礼明细礼物图片
                appMingXiSongLiService.updateGiftData(sGift.getId(), sGift.getPicture(), appGift.getGiftname());
            } else {
                if (StringUtils.isNotBlank(appGift.getSvgaaddress())) {
                    String gifteffects = appGift.getSvgaaddress().substring(appGift.getSvgaaddress().indexOf("/test/") + 6, appGift.getSvgaaddress().indexOf(".svga"));
                    appGift.setGifteffects(gifteffects);
                }

                //处理图片
                String newfilePath = "";
                Map map = FileUtil.aliyunOSSUpload(appGift.getPicture(), "");
                if (map.get("st").equals("0")) {
                    newfilePath = (String) map.get("data");
                }
                if (StringEx.isNotNull(newfilePath)) {
                    appGift.setPicture(newfilePath);
                }
                appGift.setStatus(appGift.getStatus() == null ? Constants.shiFou_STATE_FOU : appGift.getStatus());
                appGift.setShifouquanfu(appGift.getShifouquanfu() == null ? Constants.shiFou_STATE_FOU : appGift.getShifouquanfu());
                appGift.setShifouguizu(appGift.getShifouguizu() == null ? Constants.shiFou_STATE_FOU : appGift.getShifouguizu());
                appGift.setCreatetime(new Date());
                afterGiftService.save(appGift);
            }
            return this.sucessJSON("保存成功");
        } catch (Exception e) {
            logger.error("编辑礼物信息异常", e);
            return this.errorJSON("系统繁忙");
        }
    }
}
